import os.path
import time
from datetime import datetime
from  apilib.component import compManager , TComp

class TZnVarInfo:
    def __init__(self , owener , var ):
        self.owner : TPluginInZnVariant= owener
        self.info = var
        self.logs =[]
    def setLog(self , var):
        try:
            #self.logs.append(var)
            self.saveDay(var)
        except Exception as er:
            compManager.log(er)
    def saveDay (self, var ):
        res ={}
        try:
            rootPath = self.owner.compSettings['dataPath']
            appCode= "znData/variantLog"
            sysCode = self.info['sysCode']
            deviceCode = self.info['deviceCode']
            varId = self.info['varId']
            day = datetime.now().strftime("%Y%m%d")
            fnPath = f"{rootPath}/{appCode}/{sysCode}/{deviceCode}/{varId}"
            if not os.path.exists(fnPath) :
                os.makedirs(fnPath,0x777)
            fn = os.path.join(fnPath , f"{day}.csv")
            tm= var['v']
            v = var['t']
            varData = f"{varId},{tm},{v}\n"
            if not os.path.exists(fn):
                with open(fn ,"w" , encoding='utf-8') as f :
                    f.write(varData)
            else:
                with open(fn ,"a" , encoding='utf-8') as f :
                    f.write(varData)
        except Exception as er :
            self.owner.manager.log(er)
        return res
    def getDayFn (self,  dateStr ):
        res = ""
        try:
            rootPath = self.owner.compSettings['dataPath']
            appCode= "znData/variantLog"
            sysCode = self.info['sysCode']
            deviceCode = self.info['deviceCode']
            varId = self.info['varId']
            res = f"{rootPath}/{appCode}/{sysCode}/{deviceCode}/{varId}/{dateStr}.csv"
        except Exception as er :
            self.owner.manager.log(er)
        return res
class TPluginInZnVariant ( TComp):
    def __init__(self):
        super().__init__()
        self.handlers={
            "updateVariants" :self.updateVariants,
            "getReal": self.getReal,
            "getVarDayValues": self.getVarDayValues
        }
        self.autoStartServices={}
        self.variants ={}
        self.varLogs = {}
    def updateVariants(self , variantList):
        res ={}
        try:
            for var in variantList:
                varId = var['varId']
                if varId in self.variants.keys():
                    self.variants[varId].info = var
                else:
                    self.variants[varId]= TZnVarInfo(self,var)
                self.variants[varId].saveDay(var)
        except Exception as er :
            self.manager.log(er)
        return res
    def getReal(self , varIdList):
        res ={}
        try:
            for varId in varIdList:
                if varId in self.variants.keys():
                    var = self.variants[varId].info
                    res[varId] = {
                        "t": var['t'],
                        "v": var['v']
                    }
        except Exception as er :
            self.manager.log(er)
        return res
    def getVarDayValues(self , varId ,dateStr):
        res = ""
        try:
            if varId in self.variants.keys():
                var = self.variants[varId]
                fn = var.getDayFn(dateStr)
                if os.path.exists(fn):
                    with open(fn ,'r', encoding='utf-8') as f :
                        res = f.read()
        except Exception as er :
            self.manager.log(er)
        return res
_settings={
    "rootPath":"/"
}
compManager.registComponentType('TPluginInZnVariant' , TPluginInZnVariant , _settings)